import React, { useEffect, useState } from 'react';
import { Form, Input } from 'antd';
import { turnoverChildren } from '@/pages/WorkFlow/components/FormControls/formConfig/custom/turnover';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { getEmployeeInfo } from './service';

const { Item } = Form;

const TurnoverProcess = ({ form, employeeCode, dataSource }) => {
    const { getFieldDecorator } = form;
    const [list, setList] = useState([]);

    // 获取申请人个人信息
    const fetchEmployeeInfo = async uCode => {
        const { data, code } = await getEmployeeInfo(uCode);
        if (code === 10000) {
            const { dutyCode } = Array.isArray(data) ? data[0] : {};
            form.setFieldsValue({ dutyCode });
            if (!Object.keys(dataSource.children[0]).includes('initialValue')) {
                const c = dataSource.children.map(v => ({
                    ...v,
                    initialValue: data[0][v.formId]
                }));
                setList(c);
            }
        }
    };

    useEffect(() => {
        if (employeeCode) {
            fetchEmployeeInfo(employeeCode);
        } else {
            setList(turnoverChildren);
        }
    }, [employeeCode]);

    useEffect(() => {
        if (dataSource) {
            setList(dataSource.children);
        } else {
            setList(turnoverChildren);
        }
    }, [dataSource]);

    return (
        <>
            {list.map(v => {
                if (v.tag === 'Vacation') {
                    v.options.employeeCode = employeeCode;
                }

                return (
                    <Item label={v.label} key={v.formId}>
                        {getFieldDecorator(v.formId, {
                            initialValue: v.initialValue,
                            rules: v.rules
                        })(<AutoRenderComponent form={form} config={v} />)}
                    </Item>
                );
            })}
            <Item style={{ display: 'none' }}>
                {getFieldDecorator('employeeCode', {
                    initialValue: employeeCode
                })(<Input />)}
                {getFieldDecorator('dutyCode')(<Input />)}
            </Item>
        </>
    );
};

export default TurnoverProcess;
